package com.cjq.allservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjq.allservice.entity.Activity;
import com.cjq.allservice.entity.User;
import com.cjq.allservice.entity.vo.ActivityQuery;
import com.cjq.allservice.entity.vo.UserQuery;
import com.cjq.allservice.service.UserService;
import com.cjq.utils.R;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjq
 * @since 2022-01-11
 */
@RestController
@RequestMapping("/allservice/user")
@CrossOrigin
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation("用户注册进行用户添加")
    @PostMapping("/addUser")
    public R addUser(@RequestBody User user){
        boolean save = userService.save(user);
        if (save==true){
            return R.succ().message("添加成功！");
        }else{
            return R.fail().message("添加失败！");
        }
    }

    @ApiOperation("用户进行登录")
    @PostMapping("/userLogin")
    public R userLogin(@RequestParam(value = "phone") String phone,@RequestParam(value = "password") String password){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone",phone);
        User user = userService.getOne(wrapper);
        if (user==null){
            return R.succ().message("用户不存在");
        }else {
            if (password.equals(user.getUserPassword())){
                return R.succ().data("userId",user.getUserId()).message("登录成功！");
            }else {
                return R.succ().message("密码错误！");
            }
        }
    }


    @ApiOperation("显示所有用户数据")
    @GetMapping("/getAllUser")
    public R getAllUser(){
        List<User> list = userService.list();
        return R.succ().data("userList",list);
    }

    @ApiOperation("对用户账号进行禁用操作")
    @PostMapping("/updateUserStatus")
    private R updateUserStatus(@RequestParam String userId){
        User user = userService.getById(userId);
        if (user.getStatus()==1){
            user.setStatus(0);
        }else{
            user.setStatus(1);
        }

        boolean b = userService.updateById(user);
        if (b==true){
            return R.succ().message("修改成功！");
        }else {
            return R.fail().message("修改失败！");
        }
    }


    @ApiOperation("根据用户id获取用户信息")
    @GetMapping("/getUserInfoByUserId")
    public R getUserInfoByUserId(@RequestParam String userId){
        User user = userService.getById(userId);
        user.setUserPassword(null);
        return R.succ().data("userInfo",user);
    }


    @ApiOperation("修改用户密码")
    @PostMapping("/updatePasswordByUserId")
    public R updatePasswordByUserId(@RequestParam String userId,@RequestParam String newPassword){
        User user = userService.getById(userId);
        user.setUserPassword(newPassword);
        boolean b = userService.updateById(user);
        if (b==true){
            return R.succ().message("修改成功！");
        }else {
            return R.fail().message("修改失败！");
        }
    }


    @ApiOperation("条件查询用户带分页")
    //条件查询带分页
    @PostMapping ("pageUserCondition/{current}/{limit}")
    public R pageUserCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) UserQuery userQuery){
        Page<User> page=new Page<>(current,limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        //多条件组合查询
        String id = userQuery.getUserId();
        String name = userQuery.getUserName();
        String phone=userQuery.getUserPhone();
        if (!StringUtils.isEmpty(id)){
            wrapper.like("user_id",id);
        }
        if (!StringUtils.isEmpty(name)){
            wrapper.like("user_name",name);
        }
        if (!StringUtils.isEmpty(phone)){
            wrapper.like("user_phone",phone);
        }
        wrapper.orderByDesc("create_time");

        userService.page(page,wrapper);
        long total=page.getTotal();
        System.out.println(total);
        List<User> records = page.getRecords();
        HashMap map = new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return R.succ().data(map);
    }



    @ApiOperation("将所有用户的信息导出到excel文件")
    @GetMapping("/exportUsersInfo")
    public void exportDoctorsInfo(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String date= dateFormat.format(new Date()).toString();
        HSSFSheet sheet = workbook.createSheet(date + "allActivitys");

        final List<User> allUsers; //要导出的数据
        allUsers= userService.list();

        // 设置要导出的文件的名字
        String fileName = "AllUsers" + ".xls";

        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"序号","ID","名称", "手机","性别","昵称","省份","城市","身高","体重","头像","创建时间"};
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (User user : allUsers) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(rowNum);
            row1.createCell(1).setCellValue(user.getUserId());
            row1.createCell(2).setCellValue(user.getUserName());
            row1.createCell(3).setCellValue(user.getUserPhone());
            if (user.getUserSex()==0) {
                row1.createCell(4).setCellValue("女");
            }else{
                row1.createCell(4).setCellValue("男");
            }
            row1.createCell(5).setCellValue(user.getUserNickname());

            row1.createCell(6).setCellValue(user.getUserProvince());
            row1.createCell(7).setCellValue(user.getUserCity());
            row1.createCell(8).setCellValue(user.getUserHeight());
            row1.createCell(9).setCellValue(user.getUserWeight());
            row1.createCell(10).setCellValue(user.getCreateTime());
            row1.createCell(11).setCellValue(user.getAvatar());

            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}

